<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="声纹" prop="name">
        <el-select @change="handleQuery" style="width:200px;" v-model="queryParams.audioToneId" placeholder="请选择声纹">
          <el-option value="-1" label="所有" />
          <el-option :value="item.id" :label="item.name" :key="item.id" v-for="item in audioToneList" />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入音频的描述"
          clearable
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="标签名" prop="tagIdArray">
        <el-input
          v-model="queryParams.tagName"
          placeholder="请输入标签名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="关键字" prop="keyWordIdArray">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['lm:audio:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openBatchForm"
          v-hasPermi="['lm:audio:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 批量新增
        </el-button>
        <el-button
          type="danger"
          plain
          @click="openDeleteBatchForm"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 批量删除
        </el-button>
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          @click="handleExport"-->
<!--          :loading="exportLoading"-->
<!--          v-hasPermi="['lm:audio:export']"-->
<!--        >-->
<!--          <Icon icon="ep:download" class="mr-5px" /> 导出-->
<!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      v-model:selection="selectedRows"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="名字" align="center" prop="name" />
      <el-table-column label="描述" align="center" prop="textDesc" />
      <el-table-column label="音频文件" align="center" prop="fileId" >
        <template #default="scope">
          <span v-if="scope.row.fileId">
            <a style="margin-right:12px;text-decoration:none;" @click="downloadFile(scope.row)" href="javascript:void(0)">
              下载
            </a>
            <a style="text-decoration:none;" class="play-btn" @click="playFile(scope.row)" href="javascript:void(0)">
              播放
            </a>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="标签" align="center" prop="tagIdArray" >
        <template #default="scope">
          <span :key="item.id" v-for="(item,index) in scope.row.tagIdArray">
            {{item.tagName}}{{index!=scope.row.tagIdArray.length-1?'，':''}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="关键字" align="center" prop="keyWordIdArray" >
        <template #default="scope">
          <span :key="item.id" v-for="(item,index) in scope.row.keyWordIdArray">
            {{item.keyWord}}{{index!=scope.row.keyWordIdArray.length-1?'，':''}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="音频时长，单位是秒" align="center" prop="audioTime" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['lm:audio:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['lm:audio:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AudioForm  ref="formRef" @success="getList" />
  <AudioBatchForm  ref="batchFormRef" @success="getList" />
  <DeleteAudioBatchForm  ref="deleteBatchFormRef" @success="getList" />
  <SimpleAudioPlayer ref="simpleAudioPlayerRef" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { AudioApi, AudioVO } from '@/api/lm/audio'
import { AudioToneApi } from '@/api/resource/audiotone';
import AudioForm from './AudioForm.vue'
import AudioBatchForm from './AudioBatchForm.vue'
import DeleteAudioBatchForm from './DeleteAudioBatchForm.vue'
import {TagApi} from "@/api/lm/tag";
import {KeyWordApi} from "@/api/lm/keyword";
import SimpleAudioPlayer from "@/views/audio/components/SimpleAudioPlayer.vue";
import {useAppStore} from "@/store/modules/app";

/** 音频 列表 */
defineOptions({ name: 'LmAudio' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const appStore = useAppStore()
const loading = ref(true) // 列表的加载中
const visible = ref(true) // 列表的加载中
const list = ref<AudioVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const tagList = ref([]) // 标签列表
const keywordList = ref([]) // 关键字列表
const audioToneList = ref([]) // 关键字列表
const simpleAudioPlayerRef = ref();
const queryParams = reactive({
  pageNo: 1,
  audioToneId: "-1",
  pageSize: 30,
  name: undefined,
  tagName: undefined,
  keyWord: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const selectedRows = ref([]);

const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val;
};

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    if(!audioToneList.value.length) {
      const audioToneData = await AudioToneApi.getAudioTonePage({pageNo: 1, pageSize: 100});
      audioToneList.value = audioToneData.list;
      if(audioToneData.list.length) {
        queryParams.audioToneId = audioToneData.list[0].id;
      }
    }

    let param = {
      ...queryParams
    };
    if(param.audioToneId === "-1") {
      delete param.audioToneId
    }
    const data = await AudioApi.getAudioPage(param)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

function downloadFile(item) {
  window.open(item.fileUrl);

  // // 下载文件
  // let fileUrl = item.fileUrl;
  // axiosConfig.download({
  //   url: fileUrl
  // }).then(res=> {
  //   download0(res, item.fileId, res.type);
  // }).catch(res=> {
  //   console.log(res);
  // })
}

function playFile(item) {
  simpleAudioPlayerRef.value.playAudio(item.fileUrl);
  // playAudio(item.fileUrl);
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.tagName = undefined;
  queryParams.keyWord = undefined;
  if(audioToneList.value.length) {
    queryParams.audioToneId = audioToneList.value[0].id;
  } else {
    queryParams.audioToneId = "-1";
  }
  queryFormRef.value.resetFields();
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id, {
    tagList: tagList.value,
    keywordList: keywordList.value
  })
}

const batchFormRef = ref();
const openBatchForm = () => {
  batchFormRef.value.open({
    tagList: tagList.value,
    audioToneList: audioToneList.value,
    audioToneId: queryParams.audioToneId === "-1" ? audioToneList.value[0].id : queryParams.audioToneId
  })
}

const deleteBatchFormRef = ref();
const openDeleteBatchForm = ()=> {
  if(!selectedRows.value.length) {
    return message.warning("请选择要删除的音频");
  }

  deleteBatchFormRef.value.open({
    list: selectedRows.value
  })
}


/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AudioApi.deleteAudio(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AudioApi.exportAudio(queryParams)
    download.excel(data, '音频.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList();
  // 获取标签列表
  TagApi.getTagPage({
    pageNo: 1,
    pageSize: 100
  }).then(e=> {
    tagList.value = e.list;
  })
  // 获取关键字列表
  KeyWordApi.getKeyWordPage({
    pageNo: 1,
    pageSize: 100
  }).then(e=> {
    keywordList.value = e.list;
  });

  appStore.setSimpleAudioPlayer(simpleAudioPlayerRef.value);
})
</script>
